<#include "/includes/vars.inc"> 
<@pp.dropOutputFile />
<#list entities.entity as entity>
    <#assign entityName = entity.@name>
	<#assign fileName = "${javaDir}${packageDir}/web/converter/"+entityName?cap_first+"Converter.java">
	<#if !pp.outputFileExists(fileName)>
		<@pp.changeOutputFile name="${fileName}" />
   
package ${project.@rootPackage}.web.converter;

import ${project.@rootPackage}.domain.${entityName};
import ${project.@rootPackage}.web.${entityName}Controller;
import ${project.@rootPackage}.web.util.JsfUtil;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

    @FacesConverter(forClass = ${entityName}.class, value = "${entityName?uncap_first}Converter")
    public  class ${entityName}Converter implements Converter {
    	protected static final Logger logger = Logger.getLogger("${entityName}Converter");
    
        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            
            //logger.log(Level.INFO, "getAsObject: {0}", value);
            if (value == null || value.length() == 0 || value.equals("---")) {
                return null;
            }
            ${entityName}Controller controller = (${entityName}Controller)JsfUtil.getBean("${entityName?uncap_first}Controller");
            Object o = null;
            try {
                o = controller.getService().findById(Long.valueOf(value));
            } catch (Exception e) {
                o=null;
                logger.log(Level.SEVERE, "Cant convert User id: {0}", value);
            }
            //logger.log(Level.INFO, "getAsObject: {0}", o);
            return o;
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            //logger.log(Level.INFO, "getAsString: {0}", object);
            if (object == null) {
                return null;
            }
            if (object instanceof ${entityName}) {
                ${entityName} o = (${entityName}) object;
	            if (o.getId() == null) {
	                return null;
	            } else {
	                return o.getId().toString();
	            }
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ${entityName}.class.getName());
            }
        }
    }
	</#if>
</#list>
